package com.sinacom.ibuilding.action;



import java.io.File;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
//import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.sinacom.ibuilding.beans.Member;
import com.sinacom.ibuilding.beans.Message;
import com.sinacom.ibuilding.beans.Role;
import com.sinacom.ibuilding.service.MemberService;
import com.sinacom.ibuilding.service.MessageService;
import com.sinacom.ibuilding.util.Constants;
import com.sinacom.ibuilding.util.Helper;
import com.sinacom.ibuilding.util.PageModel;

public class MessageAction {
	
	private MemberService memberService = new MemberService();
	private MessageService messageService = new MessageService();
	private int page;
	private PageModel pageModel;
	private Message message;
	
	private File attach;
	private String attachFileName;
	private String attachContentType;
	
	private String filePath;
	private String messageId;
	
	private List memberList;
	private List contactList;
	private Map contactMap;
	
	private List roleTree;
	public String receivebox()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		if(page < 1){
			page = 1;
		}
		pageModel = messageService.getMsgReceiveBox(member, page);
		return "receivebox";
	}
	
	public String sendbox()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		if(page < 1){
			page = 1;
		}
		pageModel = messageService.getMsgSendBox(member, page);
		return "sendbox";
	}
	
	public String input()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		Role r = member.getRole();
		setRoleTree(r);
		/*if(r != null){
			List list = (List) Constants.cacheMap.get("roleTree");
			if(r.getVisituser() != null && r.getVisituser().intValue()==1){
				roleTree = list;
			}else if(r.getVisituser() != null && r.getVisituser().intValue()==2){
				if(list != null && list.size() > 0){
					for (int i = 0; i < list.size(); i++) {
						Role role = (Role) list.get(i);
						if("1".equals(role.getId())){
							if(roleTree == null) roleTree = new ArrayList();
							roleTree.add(role);
						}
					}
				}
			}
			
			
		}
		
		
		if(roleTree !=null && roleTree.size() > 0){ 
			for (int i = 0; i < roleTree.size(); i++) {
				Role role = (Role) roleTree.get(i);
				role.setMemberList(memberService.getMemberByRole(role.getId()));
				if(role != null && role.getRoleList() != null && role.getRoleList().size() > 0){
					for (int j = 0; j < role.getRoleList().size(); j++) {
						Role role2 = (Role) role.getRoleList().get(j);
						role2.setMemberList(memberService.getMemberByRole(role2.getId()));
						if(role2 != null && role2.getRoleList() != null && role2.getRoleList().size() > 0){
							for (int k = 0; k < role2.getRoleList().size(); k++) {
								Role role3 = (Role) role2.getRoleList().get(k);
								role3.setMemberList(memberService.getMemberByRole(role3.getId()));
							}
						}
					}
				}
			}
		}*/
		
		return "input";
	}
	
	public String edit()throws Exception{
		message = messageService.getMessageById(messageId);
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		Role r = member.getRole();
		/*if(r != null){
			List list = (List) Constants.cacheMap.get("roleTree");
			if(r.getVisituser() != null && r.getVisituser().intValue()==1){
				roleTree = list;
			}else if(r.getVisituser() != null && r.getVisituser().intValue()==2){
				if(list != null && list.size() > 0){
					for (int i = 0; i < list.size(); i++) {
						Role role = (Role) list.get(i);
						if("1".equals(role.getId())){
							if(roleTree == null) roleTree = new ArrayList();
							roleTree.add(role);
						}
					}
				}
			}
			
			
		}
		
		
		if(roleTree !=null && roleTree.size() > 0){
			for (int i = 0; i < roleTree.size(); i++) {
				Role role = (Role) roleTree.get(i);
				role.setMemberList(memberService.getMemberByRole(role.getId()));
				if(role != null && role.getRoleList() != null && role.getRoleList().size() > 0){
					for (int j = 0; j < role.getRoleList().size(); j++) {
						Role role2 = (Role) role.getRoleList().get(j);
						role2.setMemberList(memberService.getMemberByRole(role2.getId()));
						if(role2 != null && role2.getRoleList() != null && role2.getRoleList().size() > 0){
							for (int k = 0; k < role2.getRoleList().size(); k++) {
								Role role3 = (Role) role2.getRoleList().get(k);
								role3.setMemberList(memberService.getMemberByRole(role3.getId()));
							}
						}
					}
				}
			}
		}
		*/
		setRoleTree(r);
		
		request.setAttribute("rmember", Helper.getRmember(message.getRmember()));
		return "input";
	}
	public void setRoleTree(Role r){
		if(r != null){
			List list = (List) Constants.cacheMap.get("roleTree");
			if(r.getVisituser()!=null && r.getVisituser().intValue()==1){
				roleTree = list;
			}else if(r.getVisituser() != null && r.getVisituser().intValue() == 2){
				if(list != null && list.size() > 0){
					for (int i = 0; i < list.size(); i++) {
						Role role = (Role) list.get(i);
						if("1".equals(role.getId())){
							if(roleTree == null) roleTree = new ArrayList();
							roleTree.add(role);
						}
					}
				}
			}
			
			
		} 
		if(roleTree !=null && roleTree.size() > 0){
			for (int i = 0; i < roleTree.size(); i++) {
				Role role = (Role) roleTree.get(i);
				List list1 = memberService.getMemberByRole(role.getId());
				if(list1 != null && list1.size() > 0){
					role.setMemberList(list1);
					role.setHasMember(Boolean.TRUE);
				}else{
					role.setHasMember(Boolean.FALSE);
				}
				if(role != null && role.getRoleList() != null && role.getRoleList().size() > 0){
					for (int j = 0; j < role.getRoleList().size(); j++) {
						Role role2 = (Role) role.getRoleList().get(j);
						List list2 = memberService.getMemberByRole(role2.getId());
						if(list2 != null && list2.size() > 0){
							role2.setMemberList(list2);
							role.setHasMember(Boolean.TRUE);
							role2.setHasMember(Boolean.TRUE);
						}else{
							role2.setHasMember(Boolean.FALSE);
						}
						if(role2 != null && role2.getRoleList() != null && role2.getRoleList().size() > 0){
							for (int k = 0; k < role2.getRoleList().size(); k++) {
								Role role3 = (Role) role2.getRoleList().get(k);
								List list3 = memberService.getMemberByRole(role3.getId());
								if(list3 != null && list3.size() > 0){
									role3.setMemberList(list3);
									role.setHasMember(Boolean.TRUE);
									role2.setHasMember(Boolean.TRUE);
									role3.setHasMember(Boolean.TRUE);
								}else{
									role3.setHasMember(Boolean.FALSE);
								}
							}
						}
					}
				}
			}
		}
	}
	
	public String reply()throws Exception{
		message = messageService.getMessageById(messageId);
		message.setRmember(message.getSmember());
		HttpServletRequest request = ServletActionContext.getRequest(); 
		request.setAttribute("rmember", Helper.getRmember(message.getRmember()));
		return "input";
	}
	
	
	
	public String forward()throws Exception{
		message = messageService.getMessageById(messageId);
		message.setRmember(null);
		return "input";
	}
	
	public String readmsg()throws Exception{
	    messageService.readMessage(messageId);
		message = messageService.getMessageById(messageId);
		HttpServletRequest request = ServletActionContext.getRequest(); 
		request.setAttribute("rmember", Helper.getRmember(message.getRmember()));
		return "readmsg";
	}
	
	public String send()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();  
        Role role = member.getRole();
        if(role != null && role.getMsgsend() != null && role.getMsgsend().booleanValue()){
        	if(messageService.sendMsg(member, message,true)){
  			  map.put("success", "true");
  		      map.put("msg", "发送成功");
	  		}else{
	  			
	  			map.put("success", "false");
	  		    map.put("msg", "发送失败");
	  		}
        }else{
        	map.put("success", "false");
  		    map.put("msg", "您没有短信发送权限");
        }
		
		
      
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	
	public String resend()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		Member member = (Member) request.getSession().getAttribute("member");
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();  
        Message m = messageService.getMessageById(messageId);
        if(m != null){
        	 if(messageService.sendMsg(member, m,true)){
             	map.put("success", "true");
                 map.put("msg", "发送成功");
                 pw.print(JSONObject.fromObject(map));
                 return null;
             }
        }
       
        map.put("success", "false");
        map.put("msg", "发送失败");
        pw.print(JSONObject.fromObject(map));
        return null;
	}
	
	public String uploadAttach()throws Exception{
		ServletContext context = ServletActionContext.getServletContext();
		String targetDirectory = context.getRealPath("/attach");   
		DateFormat format = new SimpleDateFormat("yyyyMMdd");   
        String formatDate = format.format(new Date());
        long time = (new Date()).getTime();
        File target = new File(targetDirectory+"/"+formatDate+"/"+time, attachFileName);   
           
        FileUtils.copyFile(attach, target); 
        
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        map.put("fileName", attachFileName);
        map.put("filePath", "/attach/"+formatDate+"/"+time+"/"+attachFileName);
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	
	public String cancelAttach()throws Exception{
//	    取消删除上传的文件
		/*if(!StringUtils.isEmpty(filePath)){ 
			ServletContext context = ServletActionContext.getServletContext();
			String realPath = context.getRealPath("/");
			File f = new File(realPath+filePath);
			if(f.exists()){
				f.delete();
			}
		}*/
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        map.put("success", "true");
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	
	public String delete()throws Exception{
	    HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member member = (Member) request.getSession().getAttribute("member");
        if(member != null){
            try{
                Message message = messageService.getMessageById(messageId);
                if(message.getMember().equals(member.getId())){
                    messageService.deleteMessage(messageId);   
                    map.put("success", "true");
                }else{
                    map.put("success", "false");
                    map.put("msg", "您没有删除该短信的权利！");
                }
                
            }catch(Exception e){
                e.printStackTrace();
                map.put("success", "false");
                map.put("msg", "删除短信失败!");
            }
        }else{
            map.put("success", "false");
            map.put("msg", "您还没有登录!");
        }
        
        pw.print(JSONObject.fromObject(map));
	    return null;
	}
	
	
	
	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public PageModel getPageModel() {
		return pageModel;
	}

	public void setPageModel(PageModel pageModel) {
		this.pageModel = pageModel;
	}
	
	public Message getMessage() {
		return message;
	}

	public void setMessage(Message message) {
		this.message = message;
	}
	
	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	
	
	

	public File getAttach() {
		return attach;
	}

	public void setAttach(File attach) {
		this.attach = attach;
	}

	public String getAttachFileName() {
		return attachFileName;
	}

	public void setAttachFileName(String attachFileName) {
		this.attachFileName = attachFileName;
	}

	public String getAttachContentType() {
		return attachContentType;
	}

	public void setAttachContentType(String attachContentType) {
		this.attachContentType = attachContentType;
	}

	public MessageService getMessageService() {
		return messageService;
	}

	public void setMessageService(MessageService messageService) {
		this.messageService = messageService;
	}
	
	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	

	public String getMessageId() {
		return messageId;
	}

	public void setMessageId(String messageId) {
		this.messageId = messageId;
	}
	
	

	public List getMemberList() {
		return memberList;
	}

	public void setMemberList(List memberList) {
		this.memberList = memberList;
	}
	

	public List getContactList() {
		return contactList;
	}

	public void setContactList(List contactList) {
		this.contactList = contactList;
	}
	
	public Map getContactMap() {
		return contactMap;
	}

	public void setContactMap(Map contactMap) {
		this.contactMap = contactMap;
	}
	

	public List getRoleTree() {
		return roleTree;
	}

	public void setRoleTree(List roleTree) {
		this.roleTree = roleTree;
	}

	public static void main(String[] args) {
		System.out.println(DigestUtils.md5Hex("111111"));
	}
	
	
}
